<template>
  <div class="filter-selected-value">
    <div
      ref="optionsContent"
      :class="{
        content: true,
      }"
    >
      <div
        v-for="item in jsonKeyOptions"
        :key="item"
        class="options-item"
        :title="`${item}`"
      >
        <a-checkbox
          size="small"
          :checked="selectedJsonKey.includes(item)"
          @change="onSelectJsonKey($event, item)"
          >{{ `${item}` }}</a-checkbox
        >
      </div>
      <div v-if="isLoading" style="text-align: center;"><a-spin /></div>
    </div>
  </div>
</template>

<script lang="ts">
/**
 * 2021.7 json 解析
 */
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import { apiGetJsonKeysOrArrayIndex } from '@/api/data-clean'
import { IColumn, IKeyValueStore } from '@/store/modules/dataview'
import { StatisticsAction } from '@/util/data-selection-actions'

@Component
export default class JsonParse extends Vue {
  @Prop() requestParams: any
  @Prop() column!: IColumn
  @Prop() editData!: any
  @Prop({ default: false }) isEdit!: boolean
  @Prop({ default: '' }) parentTableName!: boolean

  private isLoading: boolean = false // loading

  private jsonKeyOptions: any[] = [] // json 对象一级 key
  private selectedJsonKey: (string | null)[] = []

  mounted() {
    this.getJsonKeyOptions()
  }

  @Watch('editData', { immediate: true, deep: true })
  private onCurrentHistory(newValue: IKeyValueStore) {
    if (!newValue || !this.isEdit) {
      return
    }
    const history = newValue.data
    if (
      history.actionType === StatisticsAction.jsonParse &&
      history.col === this.column.name
    ) {
      this.selectedJsonKey = history.key
      this.getJsonKeyOptions() // 编辑模式下选项是基于上一个表的查询，需要刷新
    }
  }

  /**
   * 获取 json 列所有 key
   * @param parameters
   * @private
   */
  private async getJsonKeyOptions(parameters?: any) {
    this.isLoading = true
    const requestParameters = {
      col: this.requestParams.name,
      type: 'json',
      table: this.requestParams.table,
    }
    // 编辑模式下，获取的选项是基于上一个记录的表进行查询
    if (this.isEdit) {
      requestParameters.table = this.parentTableName // 编辑状态下是基于上一条记录的表名来进行筛选
    }
    // 更新 key options
    const response = await apiGetJsonKeysOrArrayIndex({
      data: {
        ...requestParameters,
        ...parameters,
      },
    })
    this.isLoading = false
    if (!response.data.success) {
      this.$message.error(response.data.message)
      return
    }
    const { result } = response.data
    this.jsonKeyOptions = result.index
  }

  /**
   * 修改 json key 选择状态
   */
  public onSelectJsonKey(event: any, key: string) {
    const { checked } = event.target
    if (checked) {
      this.selectedJsonKey = [...this.selectedJsonKey, key]
    } else {
      this.selectedJsonKey = this.selectedJsonKey.filter((item) => item !== key)
    }
    if (this.selectedJsonKey.length > 0) {
      this.emitJsonParseParams()
    } else {
      this.emitJsonParseParams('reset')
    }
  }

  /**
   * 抛出去清洗动作参数（对象解析）
   */
  public emitJsonParseParams(type?: string) {
    if (type === 'reset') {
      this.$emit('on-filter-params-reset')
    } else {
      this.$emit('on-filter-params-change', {
        data: {
          action: 'JSON_PARSE',
          col: this.column.name,
          key: [
            // 抛出最终用于解析出的选项值（keys）
            ...this.selectedJsonKey,
          ],
          description: `对象解析${
            this.selectedJsonKey.length > 1
              ? `共${this.selectedJsonKey.length}个值`
              : `key:${this.selectedJsonKey[0]}`
          }`,
          actionType: StatisticsAction.jsonParse, // 筛选模式下action都为FILTER，所以需要增加 actionType 辅助前端区分
        },
      })
    }
  }
}
</script>

<style lang="less" scoped>
.filter-selected-value {
  height: 100%;

  .header {
    align-items: center;
    background-color: #fff;
    border-bottom: 1px solid rgba(233, 233, 233, 0.8);
    color: #373b52;
    display: flex;
    font-size: 14px;
    height: 25px;
    justify-content: space-between;
    line-height: 26px;
    padding: 0 12px;
    width: 100%;

    .icon {
      cursor: pointer;
      padding: 8px 12px 8px 0;
    }

    .tabs {
      cursor: pointer;
      display: inline-block;
      height: 25px;
      margin-right: 8px;
      padding: 0 16px;

      &.active {
        border-bottom: 2px solid #5963e5;
        color: #5963e5;
        font-weight: 500;
      }
    }
  }

  .content {
    height: calc(100% - 8px);
    margin-top: 8px;
    overflow-y: auto;
    width: 100%;
  }

  .options-item {
    height: 21px;
    width: 100%;

    /deep/ .ant-checkbox-wrapper {
      max-width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>
